import { createRouter, createWebHistory } from 'vue-router'
import Cookies from 'js-cookie'
import { useUserRoutersStore } from '@/stores/store'
import { clearStorage } from '@/utils/util'
import { genarateRouter } from '@/utils/util'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // {
    //   path: '/:pathMatch(.*)*',
    //   name: 'NotFound',
    //   component: () => import('@/views/NotFound/index')
    // },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/loginView')
    }
  ]
})
const whiteList = ["/login", "/register"];
router.beforeEach(async (to, from, next) => {
  const setRouter = useUserRoutersStore()
  const isLogin = Cookies.get('isLogin')
    if (isLogin) {
      if(to.path === "/login"){
        next();
      }else{
        if (!setRouter.routePamars.userRouters.length) {
          await setRouter.setUserRouters()
          const newRoutes = genarateRouter(setRouter.routePamars.userRouters)
          newRoutes.forEach((menu) => {
            router.addRoute(menu)
          })
          next({ ...to, replace: true })
          return
        }
        next()
      }
    } else{
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        next();
      } else {
        next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      }
    }
})

export default router
